{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 1. StuffDocumentChain\n",
   "id": "2ebeedd0b4f76ff0"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-14T13:51:50.202738Z",
     "start_time": "2025-04-14T13:51:40.989133Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.chains import (\n",
    "    StuffDocumentsChain,\n",
    "    LLMChain,\n",
    ")\n",
    "from langchain_core.documents import Document\n",
    "from langchain_ollama import ChatOllama\n",
    "llm = ChatOllama(base_url=\"http://10.2.4.31:11434\", model=\"qwen2.5:latest\")\n",
    "from langchain.prompts import PromptTemplate\n",
    "template = \"\"\"\n",
    "请对以下的诗句进行解释：\n",
    "{text}\n",
    "解释为：\n",
    "\"\"\"\n",
    "prompt = PromptTemplate(template=template, input_variables=[\"text\"])\n",
    "llm_chain = LLMChain(llm=llm, prompt=prompt)\n",
    "stuff_chain = StuffDocumentsChain(\n",
    "    llm_chain=llm_chain,\n",
    "    document_variable_name=\"text\"\n",
    ")\n",
    "doc = Document(\"白日依山尽，黄河入海流。欲穷千里目，更上一层楼。\")\n",
    "print(stuff_chain.invoke([doc])[\"output_text\"])\n"
   ],
   "id": "2271f80f5b3c6fc3",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "这首诗是唐代诗人王之涣所作的《登鹳雀楼》，全诗表达了诗人站在高处远眺时的感受与思考。下面是对诗句的具体解释：\n",
      "\n",
      "1. **白日依山尽，黄河入海流**：这两句描写了从高楼上看到的日落和河流的壮观景象。“白日”指的是太阳，“依山尽”描述了太阳慢慢沉落在群山之后的情景；“黄河”是中华民族的母亲河，“入海流”则描绘了黄河奔腾不息，最终汇入大海。这两句诗不仅展现了自然界的壮丽景观，也暗示了一种时间的流逝和历史的长河。\n",
      "\n",
      "2. **欲穷千里目，更上一层楼**：后两句表达了诗人对更高视野的追求。“欲穷千里目”意味着想要看到更远的地方，“更上一层楼”则是说要再登上更高的楼层。这不仅是字面上的动作描述，更是象征着人在面对人生挑战时，应该不断超越自我、追求更高的目标和理想。\n",
      "\n",
      "整首诗不仅描绘了壮丽的自然景象，还蕴含着积极向上的人生态度，鼓励人们在有限的生命中追求无限的可能与理想。\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 2.使用已封装好的chain",
   "id": "f6f8094d289ffe1a"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-14T14:29:00.688140Z",
     "start_time": "2025-04-14T14:28:56.266600Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.chains.summarize import load_summarize_chain\n",
    "chain = load_summarize_chain(llm, chain_type=\"stuff\", verbose=True)\n",
    "doc = Document(\"白日依山尽，黄河入海流。欲穷千里目，更上一层楼。\")\n",
    "chain.invoke([doc])"
   ],
   "id": "27aa92653cd96412",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001B[1m> Entering new StuffDocumentsChain chain...\u001B[0m\n",
      "\n",
      "\n",
      "\u001B[1m> Entering new LLMChain chain...\u001B[0m\n",
      "Prompt after formatting:\n",
      "\u001B[32;1m\u001B[1;3mWrite a concise summary of the following:\n",
      "\n",
      "\n",
      "\"白日依山尽，黄河入海流。欲穷千里目，更上一层楼。\"\n",
      "\n",
      "\n",
      "CONCISE SUMMARY:\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input_documents': [Document(metadata={}, page_content='白日依山尽，黄河入海流。欲穷千里目，更上一层楼。')],\n",
       " 'output_text': 'This poem depicts a scenic view with the sun setting behind the mountains and the Yellow River flowing into the sea. It concludes by suggesting that to see farther, one must climb higher.'}"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 3. refine\n",
    "通过循环引用LLM，将文档不断投喂，并产生各种中间答案，适合逻辑有上下文关联的文档，不适合交叉引用的文档\n"
   ],
   "id": "3b58945c49b8c19c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-14T14:43:40.771089Z",
     "start_time": "2025-04-14T14:43:40.764253Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.chains import RefineDocumentsChain, LLMChain\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "# This controls how each document will be formatted. Specifically,\n",
    "# it will be passed to `format_document` - see that function for more\n",
    "# details.\n",
    "document_prompt = PromptTemplate(\n",
    "    input_variables=[\"page_content\"],\n",
    "     template=\"{page_content}\"\n",
    ")\n",
    "document_variable_name = \"context\"\n",
    "\n",
    "# The prompt here should take as an input variable the\n",
    "# `document_variable_name`\n",
    "prompt = PromptTemplate.from_template(\n",
    "    \"Summarize this content: {context}\"\n",
    ")\n",
    "initial_llm_chain = LLMChain(llm=llm, prompt=prompt)\n",
    "initial_response_name = \"prev_response\"\n",
    "# The prompt here should take as an input variable the\n",
    "# `document_variable_name` as well as `initial_response_name`\n",
    "prompt_refine = PromptTemplate.from_template(\n",
    "    \"Here's your first summary: {prev_response}. \"\n",
    "    \"Now add to it based on the following context: {context}\"\n",
    ")\n",
    "refine_llm_chain = LLMChain(llm=llm, prompt=prompt_refine)\n",
    "chain = RefineDocumentsChain(\n",
    "    initial_llm_chain=initial_llm_chain,\n",
    "    refine_llm_chain=refine_llm_chain,\n",
    "    document_prompt=document_prompt,\n",
    "    document_variable_name=document_variable_name,\n",
    "    initial_response_name=initial_response_name,\n",
    ")"
   ],
   "id": "4dfddd5b13eabd0d",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/wk/vfsd_0ld2zdd4k_k9zlb6vrh0000gn/T/ipykernel_89517/2724078287.py:27: LangChainDeprecationWarning: This class is deprecated. Please see the migration guide here for a recommended replacement: https://python.langchain.com/docs/versions/migrating_chains/refine_docs_chain/\n",
      "  chain = RefineDocumentsChain(\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 4.MapReduce ",
   "id": "88898032139f8482"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "5d7b34716fa8c380"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langchain",
   "language": "python",
   "name": "langchain"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
